﻿using Microsoft.UI.Xaml.Input;
using System.Windows.Input;

namespace TableViewTest.AttachedProperties
{
    public partial class CommandExtensions
    {
        /// <summary>
        /// 双击属性
        /// </summary>
        public static readonly DependencyProperty DoubleClickProperty = DependencyProperty.RegisterAttached("DoubleClick", typeof(ICommand), typeof(CommandExtensions), new PropertyMetadata(false, DoubleClickChanged));
        /// <summary>
        /// 获取双击
        /// </summary>
        /// <param name="sender"></param>
        /// <returns></returns>
        public static ICommand GetDoubleClick(UIElement sender) => (ICommand)sender.GetValue(DoubleClickProperty);
        /// <summary>
        /// 设置双击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="value"></param>
        public static void SetDoubleClick(UIElement sender, ICommand value) => sender.SetValue(DoubleClickProperty, value);
        /// <summary>
        /// 双击命令参数
        /// </summary>
        public static readonly DependencyProperty DoubleClickCommandParameterProperty = DependencyProperty.RegisterAttached("DoubleClickCommandParameter", typeof(object), typeof(CommandExtensions), new PropertyMetadata(null));
        /// <summary>
        /// 获取双击命令参数
        /// </summary>
        /// <param name="sender"></param>
        /// <returns></returns>
        public static object? GetDoubleClickCommandParameter(UIElement sender) => sender.GetValue(DoubleClickCommandParameterProperty);
        /// <summary>
        /// 设置双击命令参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="value"></param>
        public static void SetDoubleClickCommandParameter(UIElement sender, object value) => sender.SetValue(DoubleClickCommandParameterProperty, value);
        /// <summary>
        /// 双击更改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private static void DoubleClickChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            if (sender is not UIElement uiElement) return;
            uiElement.DoubleTapped += UiElement_DoubleTapped;
        }
        /// <summary>
        /// 双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void UiElement_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e)
        {
            if (sender is not UIElement uiElement) return;
            ICommand doubleClickCommand = GetDoubleClick(uiElement);
            object doubleClickCommandParameter = GetDoubleClickCommandParameter(uiElement) ?? uiElement;
            if (!doubleClickCommand.CanExecute(doubleClickCommandParameter)) return;
            doubleClickCommand.Execute(doubleClickCommandParameter);
        }
    }
}
